package com.dldata.devtools30.controller.devtexcel;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSON;
import com.dldata.devtools30.businessmodel.SessionUserInfoEntity;
import com.dldata.devtools30.common.EnumUtils;
import com.dldata.devtools30.entity.DevtExcelEntity;
import com.dldata.devtools30.entity.DevtExcelLogEntity;
import com.dldata.devtools30.entity.DevtFormListtemplateEntity;
import com.dldata.devtools30.entity.DevtModelMetadataTableEntity;
import com.dldata.devtools30.enumpak.EnumMonth;
import com.dldata.devtools30.repository.devtexcel.DevtExcelDao;
import com.dldata.devtools30.repository.devtexcel.DevtExcelFieldDao;
import com.dldata.devtools30.repository.devtexcel.DevtExcelLogDao;
import com.dldata.devtools30.repository.devtexcel.DevtExcelTypeDao;
import com.dldata.devtools30.repository.metadata.DevtModelMetadataTableDao;
import com.dldata.devtools30.repository.sysform.DevtFormMetadataDao;
import com.dldata.devtools30.service.metadata.DevtModelMetadataTableService;
import com.dldata.devtools30.service.sysform.DevtFormListTemplateService;
import com.dldata.devtools30.service.sysform.DevtFormTypeService;
import com.dldata.devtools30.utils.*;
import com.dldata.devtools30.utils.DateUtil;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Timestamp;
import java.util.*;

/**
 *
 */
@Controller
@RequestMapping(value = "/DevtExcelImportController")
public class DevtExcelImportController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    DevtModelMetadataTableService metadataTableService;
    @Autowired
    DevtFormMetadataDao sysCrfFormMetadataDao;


    @Autowired
    private DevtExcelDao devtexcelDao;

    @Autowired
    DevtExcelLogDao devtExcelLogDao;

    @Autowired
    DevtExcelFieldDao devtExcelFieldDao;

    @Autowired
    DevtModelMetadataTableDao devtModelMetadataTableDao;

    @Autowired
    NamedParameterJdbcTemplate npJdbcTemplate;

    @RequestMapping(value = "/optPage")
    public String optPage(Model model, String id) {
        model.addAttribute("excelId", id);
        return "thymeleaf/devtools30/devtexcel/devtExcelImport";
    }

    @RequestMapping(value = "/toEdit")
    public String toEdit(String excelId, Model model, String month, String year) {


        model.addAttribute("excelId", excelId);
        model.addAttribute("month", month);
        model.addAttribute("year", year);


        return "thymeleaf/devtools30/devtexcel/devtExcelImportEdit";
    }

    @RequestMapping(value = "upload")
    @ResponseBody
    public String dbfileUpload(MultipartFile file, HttpServletRequest request, HttpServletResponse response, String excelId, String month, String year) {
        String name = "";
        String filename = file.getOriginalFilename();
        //获取后缀名称
        String fileNameExt = filename.lastIndexOf(".") > -1 ? filename.substring(filename.lastIndexOf(".") + 1, filename.length()) : "";
        name = fileNameExt.trim();
        if (!"xlsx".equals(name) && !"xls".equals(name)) {
            Map resultMap = new HashMap<>();
            resultMap.put("success", false);
            resultMap.put("msg", "不可上传" + fileNameExt.trim() + "格式文件");
            resultMap.put("filename", filename);
            resultMap.put("code", 1);//0表示成功，1失败

            return JSON.toJSONString(resultMap);
        }
        try {
            SessionUserInfoEntity userInfoEntity = RightUtil.getCurrentUser(request);
            DevtExcelLogEntity devtExcelLog = new DevtExcelLogEntity();
            devtExcelLog.setId(UUID.randomUUID().toString());
            devtExcelLog.setFileLength(String.valueOf(file.getSize()));
            devtExcelLog.setContentType(name);
            devtExcelLog.setExcelId(excelId);
            devtExcelLog.setFileNameOrg(filename);
            devtExcelLog.setDatacontent(Base64.encode(file.getBytes()));
            devtExcelLog.setImportTime(new Timestamp(new java.util.Date().getTime()));
            devtExcelLog.setUsername(userInfoEntity.getDevtooluser());
            devtExcelLog.setStatus(1);
            java.util.Date date = DateUtil.StringToDate(request.getParameter("year") + "-" + (request.getParameter("month").length() > 1 ? request.getParameter("month") : "0" + request.getParameter("month")), DateUtil.FORMATER_YYYY_MM);
            devtExcelLog.setCostdatatime(new Timestamp(date.getTime()));
            return JSON.toJSONString(saveJson(excelId, file.getBytes(), date,devtExcelLog));

        } catch (Exception ex) {
            logger.error("【执行" + this.getClass().getName() + ".saveFile() 方法失败 】异常：" + ex.getMessage(), ex);
            Map resultMap = new HashMap<>();
            resultMap.put("success", false);
            resultMap.put("msg", "系统错误，请稍候再试." + ex.getMessage().replace("\r", "").replace("\n", ""));
            resultMap.put("filename", filename);


            return JSON.toJSONString(resultMap);
        }


    }

    @RequestMapping("getmonthlist")
    @ResponseBody
    public Result getmonthlist(@RequestParam HashMap<String, String> param) {
        ArrayList<Object> list = new ArrayList<>();
        for (EnumMonth month : EnumMonth.values()) {
            HashMap<Object, Object> map = new HashMap<>();
            map.put("month", month.getValueObj().code);
            map.put("code", month.getValueObj().value);
            list.add(map);
        }


        return Result.ok(list);

    }

    @RequestMapping(value = "/getExcelLogList")
    @ResponseBody
    public Result getExcelLogList(String excelId, String month, String year) {
        java.util.Date date = DateUtil.StringToDate(year + "-" + (month.length() > 1 ? month : "0" + month), DateUtil.FORMATER_YYYY_MM);
        List<Map<String, Object>> devtExcelLogEntities = devtExcelLogDao.findbyCostdataTime(excelId, date);
        ArrayList<Object> list = new ArrayList<>();
        for (Map map : devtExcelLogEntities) {
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.putAll(map);
            if (hashMap.get("costdatatime") != null) {
                hashMap.put("costdatatime", DateUtil.formatFromDate(DateUtil.YYYY_MM_DD, (Date) hashMap.get("costdatatime")));
            }
            if (hashMap.get("importTime") != null) {
                hashMap.put("importTime", DateUtil.formatFromDate(DateUtil.YYYY_MM_DD, (Date) hashMap.get("importTime")));
            }
            list.add(hashMap);
        }

        return Result.ok(list);

    }


    @RequestMapping(value = "/deleteData")
    @ResponseBody
    public Result deleteData(String id, HttpServletRequest request,
                             HttpServletResponse response) throws Exception {
        String result;
        try {
            devtExcelLogDao.deleteById(id);

            return Result.ok();
        } catch (Exception ex) {

            logger.error("【执行" + this.getClass().getName() + ".delete() 方法失败 】异常：" + ex.getMessage());
            return Result.error("系统错误，请稍候再试！");
        }


    }

    @RequestMapping("downFiled")
    public void downFiled(String id, HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            DevtExcelLogEntity entity = devtExcelLogDao.findById(id).get();
            String contentType = entity.getContentType();

            response.setContentType(StringUtil.isEmptyOrLength0(contentType) ? "application/octet-stream" : contentType);
            String inputStreamFileName = entity.getFileNameOrg();
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(inputStreamFileName, "UTF-8"));

            ServletOutputStream servletOutputStream = response.getOutputStream();
            servletOutputStream.write(Base64.decode(entity.getDatacontent().getBytes()));
            servletOutputStream.flush();
        } catch (Exception e) {
            logger.error("系统错误！" + e.getMessage(), e);
        }
    }

    @RequestMapping("downModel")
    public void downModel(String excelId, HttpServletRequest request, HttpServletResponse response) throws IOException {
        DevtExcelEntity entity = devtexcelDao.getById(excelId);
        try {
            InputStream is = null;
            String filename = entity.getName() + ".xlsx";
            //获取后缀名称
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook();
            XSSFSheet wb = xssfWorkbook.createSheet("数据");
            XSSFRow xssfRow; // 行
            xssfRow = wb.getRow(entity.getHeadNum() != null ? entity.getHeadNum() - 1 : 0);
            if (xssfRow == null) {
                xssfRow = wb.createRow(entity.getHeadNum() != null ? entity.getHeadNum() - 1 : 0);
            }
            List<Map> daoByExcelId = devtExcelFieldDao.getByExcelId(excelId);
            for (int i = 0; i < daoByExcelId.size(); i++) {
                if (xssfRow.getCell(i) == null) {
                    xssfRow.createCell(i);
                }
                xssfRow.getCell(i).setCellValue(daoByExcelId.get(i).get("name").toString());

            }


            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            xssfWorkbook.write(response.getOutputStream());


        } catch (Exception e) {
            logger.error("系统错误！" + e.getMessage(), e);
        }
    }


    @RequestMapping("/read")
    public String read(@RequestParam HashMap<String, String> param, Model model) {

        model.addAttribute("id", param.get("id"));
        return "thymeleaf/devtools30/devtexcel/devtExcelRead";
    }

    @RequestMapping("/excelRead")
    public String excelRead(@RequestParam HashMap<String, String> param, Model model) {

        model.addAttribute("id", param.get("id"));
        return "thymeleaf/devtools30/devtexcel/devtExcelReadExcel";
    }

    @RequestMapping("/readList")
    @ResponseBody
    public HashMap<String, Object> readList(String id, Model model) {
        HashMap<String, Object> result = new HashMap<>();
        Result<Object> r = new Result<Object>();
        r.setCode(0);
        DevtExcelLogEntity entity = devtExcelLogDao.getById(id);
        DevtExcelEntity excelEntity = devtexcelDao.getById(entity.getExcelId());
        List<Map> daoByExcelId = devtExcelFieldDao.getByExcelId(entity.getExcelId());

        try {
            ArrayList<Object> headList = new ArrayList<>();
            String sql="select   * from "+devtModelMetadataTableDao.findById(excelEntity.getTableId()).get().getViewcode()+" where datatime>=:datatime  and datatime<=:datatime ";
            MapSqlParameterSource parameters = new MapSqlParameterSource();
            parameters.addValue("datatime",entity.getCostdatatime());
            List<Map<String, Object>> dataList = npJdbcTemplate.queryForList(sql, parameters);

            for (Map map: daoByExcelId) {
                    HashMap<Object, Object> obj = new HashMap<>();
                    obj.put("field", map.get("fieldCode"));
                    obj.put("title", map.get("fieldName"));
                    obj.put("width", 200);
                    obj.put("align", "left");
                    obj.put("sortable", true);
                    obj.put("filter", true);
                    headList.add(obj);


            }
            result.put("headList", headList);


            result.put("dataList", dataList);

        } catch (Exception e) {
            logger.error("系统错误！" + e.getMessage(), e);
            result.put("success", false);
            result.put("msg", "查看失败！");
            return result;
        }
        result.put("success", true);
        result.put("msg", "查看成功！");
        return result;
    }

    @RequestMapping("/readExcelList")
    @ResponseBody
    public HashMap<String, Object> readExcelList(String id, Model model) {
        HashMap<String, Object> result = new HashMap<>();
        Result<Object> r = new Result<Object>();
        r.setCode(0);
        DevtExcelLogEntity entity = devtExcelLogDao.getById(id);
        DevtExcelEntity excelEntity = devtexcelDao.getById(entity.getExcelId());
        byte[] decode = Base64.decode(entity.getDatacontent().getBytes());
        InputStream is = null;
        String filename = entity.getContentType();             //获取后缀名称
        try {
            is = new ByteArrayInputStream(decode);
            //获取工作薄
            Workbook wb = null;
            if (filename.equalsIgnoreCase("xls")) {
                wb = new HSSFWorkbook(is);
            } else if (filename.equalsIgnoreCase("xlsx")) {
                wb = new XSSFWorkbook(is);
            } else {
                result.put("success", false);
                result.put("msg", "查看失败！");
                return result;
            }
            //读取第一个工作页sheet
            Sheet sheet = wb.getSheetAt(0);
            //列头
            Row hender = sheet.getRow(excelEntity.getHeadNum() - 1);
            //获得对应列
            HashMap<Integer, String> nameMapNum = new HashMap<>();
            //获得对应模型名称,模型代码
            ArrayList<Object> headList = new ArrayList<>();
            for (Cell cell : hender) {
                if (!StringUtil.isEmptyOrLength0(cell.getStringCellValue())) {
                    HashMap<Object, Object> obj = new HashMap<>();
                    obj.put("field", cell.getStringCellValue());
                    obj.put("title", cell.getStringCellValue());
                    obj.put("width", "200");
                    obj.put("align", "left");
                    obj.put("sortable", true);
                    obj.put("filter", true);
                    headList.add(obj);
                    nameMapNum.put(cell.getColumnIndex(), cell.getStringCellValue());
                }
            }
            result.put("headList", headList);

            int realRowCount = sheet.getPhysicalNumberOfRows();
            Row row = null;
            ArrayList<Object> dataList = new ArrayList<>();
            for (int i = excelEntity.getDataNum() - 1; i < realRowCount; i++) {
                row = sheet.getRow(i);
                short minColIx = row.getFirstCellNum();
                short maxColIx = row.getLastCellNum();

                HashMap<Object, Object> datamap = new HashMap<>();
                for (short colIx = minColIx; colIx < maxColIx; colIx++) {
                    Cell cell = row.getCell(colIx);
                    if (cell == null || nameMapNum.get(cell.getColumnIndex()) == null) {
                        continue;
                    }
                    if (cell.getCellType() == CellType.BLANK || cell.getCellType() == CellType.ERROR || cell.getCellType() == CellType.FORMULA) {
                        datamap.put(nameMapNum.get(cell.getColumnIndex()), "");
                    } else if (cell.getCellType() == CellType.BOOLEAN) {
                        boolean booleanCellValue = cell.getBooleanCellValue();
                        datamap.put(nameMapNum.get(cell.getColumnIndex()), String.valueOf(booleanCellValue));
                    } else if (cell.getCellType() == CellType.NUMERIC) {
                        datamap.put(nameMapNum.get(cell.getColumnIndex()), new BigDecimal(cell.getNumericCellValue()));
                    } else if (cell.getCellType() == CellType.STRING) {
                        datamap.put(nameMapNum.get(cell.getColumnIndex()), cell.getStringCellValue());
                    }


                }
                dataList.add(datamap);
            }
            result.put("dataList", dataList);

        } catch (Exception e) {
            logger.error("系统错误！" + e.getMessage(), e);
            result.put("success", false);
            result.put("msg", "查看失败！");
            return result;
        }
        result.put("success", true);
        result.put("msg", "查看成功！");
        return result;
    }

    public HashMap<String,Object> saveJson(String excelId, byte[] bytes, Date date, DevtExcelLogEntity devtExcelLog) {
        HashMap<String, Object> result = new HashMap<>();
        DevtExcelEntity entity = devtexcelDao.getById(excelId);
        DevtModelMetadataTableEntity devtModelMetadataTableEntity = devtModelMetadataTableDao.findById(entity.getTableId()).get();
        InputStream is = null;
        String filename = devtExcelLog.getContentType();             //获取后缀名称
        try {
            is = new ByteArrayInputStream(bytes);
            //获取工作薄
            Workbook wb = null;
            if (filename.equalsIgnoreCase("xls")) {
                wb = new HSSFWorkbook(is);
            } else if (filename.equalsIgnoreCase("xlsx")) {
                wb = new XSSFWorkbook(is);
            } else {
                result.put("success", false);
                result.put("msg", "文件格式不符合！");
                return result;
            }
            //读取第一个工作页sheet
            Sheet sheet = wb.getSheetAt(0);
            //列头
            Row hender = sheet.getRow(entity.getHeadNum() - 1);
            //获得对应列
            List<Map> daoByExcelId = devtExcelFieldDao.getByExcelId(entity.getId());
            HashMap<String, String> nameMap = new HashMap<>();
            HashMap<String, String> codeMap = new HashMap<>();
            for (Map map : daoByExcelId) {
                nameMap.put(map.get("name").toString(), map.get("fieldName").toString());
                codeMap.put(map.get("name").toString(), map.get("fieldCode").toString());

            }

            HashMap<Integer, String> nameMapNum = new HashMap<>();
            HashMap<Integer, String> codeMapNum = new HashMap<>();
            HashMap<String, Integer> codeMaps = new HashMap<>();
            //获得对应模型名称,模型代码
            ArrayList<Object> headList = new ArrayList<>();
            for (Cell cell : hender) {
                if (!StringUtil.isEmptyOrLength0(cell.getStringCellValue()) && !StringUtil.isEmptyOrLength0(codeMap.get(cell.getStringCellValue()))) {
                    HashMap<Object, Object> obj = new HashMap<>();
                    obj.put("field", codeMap.get(cell.getStringCellValue()));
                    obj.put("title", nameMap.get(cell.getStringCellValue()));
                    obj.put("width", 200);
                    obj.put("align", "left");
                    obj.put("sortable", true);
                    obj.put("filter", true);
                    headList.add(obj);
                    nameMapNum.put(cell.getColumnIndex(), nameMap.get(cell.getStringCellValue()));
                    codeMapNum.put(cell.getColumnIndex(), codeMap.get(cell.getStringCellValue()));
                    codeMaps.put(codeMap.get(cell.getStringCellValue()),1);
                }
            }

            int realRowCount = sheet.getPhysicalNumberOfRows();
            Row row = null;
            ArrayList<HashMap<Object, Object>> dataList = new ArrayList<>();
            for (int i = entity.getDataNum() - 1; i < realRowCount; i++) {
                row = sheet.getRow(i);
                short minColIx = row.getFirstCellNum();
                short maxColIx = row.getLastCellNum();

                HashMap<Object, Object> datamap = new HashMap<>();
                for (short colIx = minColIx; colIx < maxColIx; colIx++) {
                    Cell cell = row.getCell(colIx);
                    if (cell == null || codeMapNum.get(cell.getColumnIndex()) == null) {
                        continue;
                    }
                    if (cell.getCellType() == CellType.BLANK || cell.getCellType() == CellType.ERROR || cell.getCellType() == CellType.FORMULA) {
                        datamap.put(codeMapNum.get(cell.getColumnIndex()), "");
                    } else if (cell.getCellType() == CellType.BOOLEAN) {
                        boolean booleanCellValue = cell.getBooleanCellValue();
                        datamap.put(codeMapNum.get(cell.getColumnIndex()), String.valueOf(booleanCellValue));
                    } else if (cell.getCellType() == CellType.NUMERIC) {
                        datamap.put(codeMapNum.get(cell.getColumnIndex()), new BigDecimal(cell.getNumericCellValue()));
                    } else if (cell.getCellType() == CellType.STRING) {
                        datamap.put(codeMapNum.get(cell.getColumnIndex()), cell.getStringCellValue());
                    }


                }
                dataList.add(datamap);
            }
            if (devtModelMetadataTableEntity.getStoretype().equals("普通")){
                String deletesql = "delete from  " + devtModelMetadataTableEntity.getCode() + "  where  datatime>=:datatime  and datatime<=:datatime  ";
                HashMap deleteMap = new HashMap();
                deleteMap.put("datatime", date);
                npJdbcTemplate.update(deletesql, deleteMap);


                String insertSql = getInsertSql(devtModelMetadataTableEntity, daoByExcelId, codeMaps);
                for (HashMap<Object, Object> valueMap : dataList) {
                    HashMap paraMap = new HashMap();
                    Set<Map.Entry<Object, Object>> entries = valueMap.entrySet();
                    for (Map.Entry<Object, Object> entry : entries) {
                        paraMap.put(entry.getKey(),entry.getValue());
                    }
                    if (paraMap.get("ID")==null){
                        paraMap.put("ID",UUID.randomUUID().toString());
                    }
                    paraMap.put("datatime", new Timestamp(date.getTime()));

                    npJdbcTemplate.update(insertSql, paraMap);

                }
                String updatesql = "update    devt_excel_log set status=2  where  excel_id=:excelId ";
                HashMap updateMap = new HashMap();
                updateMap.put("excelId", excelId);
                npJdbcTemplate.update(updatesql, updateMap);
                devtExcelLog.setStatus(1);
                devtExcelLogDao.save(devtExcelLog);
                result.put("success", true);
                result.put("msg", "成功！");
                return result;

            }
            String deletesql = "delete from  " + devtModelMetadataTableEntity.getCode() + "  where  _datatime>=:datatime  and _datatime<=:datatime  ";
            HashMap deleteMap = new HashMap();
            deleteMap.put("datatime", date);
            npJdbcTemplate.update(deletesql, deleteMap);
            String insertSql = " insert into  " + devtModelMetadataTableEntity.getCode() + "(id,_usercode,_createtime,_updatetime,jsondata,_datatime ) values (:id,:_usercode,:_createtime,:_updatetime,:jsondata,:datatime )";
            HashMap paraMap = new HashMap();
            paraMap.put("_usercode", RightUtil.getCurrentUser(Public.getRequest()).getDevtooluser());
            paraMap.put("_createtime", new Timestamp(System.currentTimeMillis()));
            paraMap.put("_updatetime", new Timestamp(System.currentTimeMillis()));
            paraMap.put("datatime", new Timestamp(date.getTime()));

            for (Object valueMap : dataList) {

                paraMap.put("jsondata", JSON.toJSONStringWithDateFormat(valueMap, "yyyy-MM-dd HH:mm:ss.SSS"));
                paraMap.put("id", UUID.randomUUID().toString());
                npJdbcTemplate.update(insertSql, paraMap);
            }


            String updatesql = "update    devt_excel_log set status=2  where  excel_id=:excelId ";
            HashMap updateMap = new HashMap();
            updateMap.put("excelId", excelId);
            npJdbcTemplate.update(updatesql, updateMap);
            devtExcelLog.setStatus(1);
            devtExcelLogDao.save(devtExcelLog);
        } catch (Exception e) {
            logger.error("系统错误！" + e.getMessage(), e);
            result.put("success", false);
            result.put("msg", e.getMessage());
            return result;
        }
        result.put("success", true);
        result.put("msg", "成功！");
        return result;
    }




        public String getInsertSql(DevtModelMetadataTableEntity entity,List<Map> daoByExcelId,HashMap<String, Integer> codeMaps) {
        StringBuilder insertsql=new StringBuilder();
        insertsql.append(" insert into  ");
        insertsql.append( entity.getCode()+" ( ");
        StringBuilder insertvalusSql=new StringBuilder();
        insertvalusSql.append("values  (");
            for (Map map : daoByExcelId) {
                if (codeMaps.get(map.get("fieldCode"))!=null&&codeMaps.get(map.get("fieldCode"))==1){
                    insertsql.append(map.get("fieldCode")+",");
                    insertvalusSql.append(":"+map.get("fieldCode")+",");
                }

            }
            if (!insertsql.toString().contains("ID")&&!insertsql.toString().contains("id")){
                insertsql.append(" ID,  ");
                insertvalusSql.append(":ID, ");
            }
            insertsql.append(" datatime ) ");
            insertvalusSql.append(":datatime )");
        return insertsql.append(insertvalusSql.toString()).toString();
    }
    @RequestMapping(value = "/synchronous")
    @ResponseBody
    public HashMap<String, Object> synchronous( String month, String year, String id) {
        java.util.Date date = DateUtil.StringToDate(year + "-" + (month.length() > 1 ? month : "0" + month), DateUtil.FORMATER_YYYY_MM);
        DevtExcelLogEntity byId = devtExcelLogDao.getById(id);

        return saveJson(byId.getExcelId(),Base64.decode(byId.getDatacontent().getBytes()),date,byId);

    }
}
